<?php


namespace app\shop\controller\admin;


use app\shop\common\consts\Consts;
use app\shop\controller\BaseAdminController;
use app\shop\model\chat\GroupUserModel;
use app\shop\model\file\FileModel;
use app\shop\model\order\OrderModel;
use app\shop\model\user\ChatUserModel;
use app\shop\model\user\MessageModel;
use app\shop\model\user\UserModel;
use app\shop\service\until\FileService;
use app\shop\service\user\AdminRoleService;
use app\shop\service\user\UserService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\App;
use think\facade\Db;

class ChatController extends BaseAdminController
{

    /**
     * 聊天列表
     * @return \think\response\Json
     */
    public function getChatList()
    {
        try {
            $where = [];
            $customerName = $this->request->param('customer_name', '', 'trim');
            if ($customerName) {
                $uid = UserModel::where('realname', $customerName)->value('user_id');
                $chatSignArr = GroupUserModel::where('user_id', $uid)->column('chat_sign');
                $where[] = ['chat_sign', 'in', $chatSignArr];
            }
            $departmentId = $this->request->param('department_id', '', 'trim');
            if ($departmentId) {
                $userIdArr = UserModel::where('department_id', $departmentId)->column('user_id');
                $chatSignArr = GroupUserModel::whereIn('user_id', $userIdArr)->column('chat_sign');
                $where[] = ['chat_sign', 'in', $chatSignArr];
            }
            $designName = $this->request->param('design_name', '', 'trim');
            if ($designName) {
                $uid = UserModel::where('realname', $designName)->whereIn('role_id', [Consts::DESIGN_LEADER_ID, Consts::DESIGN_ID, Consts::SERVICE_LEADER_ID])->value('user_id');
                $chatSignArr = GroupUserModel::where('user_id', $uid)->column('chat_sign');
                $where[] = ['chat_sign', 'in', $chatSignArr];
            }
            $designType = $this->request->param('design_type', '', 'trim');
            if ($designType) {
                $oid = OrderModel::where('design_type', $designType)->column('id');
                $where[] = ['order_id', 'in', $oid];
            }
            $createTime = $this->request->param('create_time', '', 'trim');
            if ($createTime) {
                $where[] = ['create_time', '>=', strtotime($createTime)];
                $where[] = ['create_time', '<', strtotime($createTime) + 86400];
            }
            $orderName = $this->request->param('order_name', '', 'trim');
            if ($orderName) {
                $orderId = OrderModel::where('order_name', "like", "%{$orderName}%")->column('id');
                $where[] = ['order_id', 'in', $orderId];
            }
            $list = ChatUserModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['order_name'] = OrderModel::where('id', $v['order_id'])->value('order_name', '');
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 聊天记录
     * @return \think\response\Json
     */
    public function getChatRecord()
    {
        try {
            $chatIdentify = $this->request->param('chat_identify');
            $list = MessageModel::where('chat_sign', $chatIdentify)
                ->with('fromUser')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['full_src'] = FileService::getFullUrl($v['content']);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 聊天记录
     * @return \think\response\Json
     */
    public function getChatInfo()
    {
        try {
            $chatSign = $this->request->param('chat_identify');
            $orderId = $this->request->param('order_id');

            if (!$chatSign && $orderId) {
                $chatSign = ChatUserModel::where('order_id', $orderId)->value('chat_sign');
            }
            $list = MessageModel::where('chat_sign', $chatSign)
                ->field('msg_id,from_user,content,type,file_id,file_cate')
                ->limit(100)
                ->order('msg_id','desc')
                ->select();
            foreach ($list as &$v) {
                $v['from_user_name'] = UserModel::withTrashed()->where('user_id', $v['from_user'])->value('realname', '');
                if ($v['file_id']) {
                    $v['full_src'] = FileService::getFullUrl($v['content']);
                }
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function download()
    {
        try {
            $chatIdentify = $this->request->param('chat_identify');
            $orderId = MessageModel::where('chat_sign', $chatIdentify)->value('order_id');
            if (!$orderId) {
                $list = MessageModel::where('chat_sign', $chatIdentify)
                    ->with('fromUser')
                    ->whereNotIn('type', ['system', 'event'])
                    ->select();
            } else {
                $list = MessageModel::where('order_id', $orderId)
                    ->with('fromUser')
                    ->whereNotIn('type', ['system', 'event'])
                    ->select();
            }
            $spreadsheet = new Spreadsheet();
            $worksheet = $spreadsheet->getActiveSheet();
            $worksheet->setCellValue("A1", '发送者');
            $worksheet->setCellValue("B1", '接收者');
            $worksheet->setCellValue("C1", '发送内容');
            $worksheet->setCellValue("D1", '发送时间');
            $i = 2;
            foreach ($list as $v) {
                $fromUserName = UserModel::where('user_id', $v['from_user'])->value('realname', '');
                $toUserName = UserModel::where('user_id', $v['to_user'])->value('realname', '');
                $content = $v['content'];
                if ($v['file_id'] > 0) {
                    $content = FileModel::where('file_id', $v['file_id'])->value('src', '');
                    $content = FileService::getFullUrl($content);
                }
                $worksheet->setCellValue("A" . $i, $fromUserName);
                $worksheet->setCellValue("B" . $i, $toUserName);
                $worksheet->setCellValue("C" . $i, $content);
                $worksheet->setCellValue("D" . $i, $v['create_time']);
                $i++;
            }
            $writer = new Xlsx($spreadsheet);
            $filename = date("YmdHis") . '聊天记录.xlsx';
            $filePrefix = 'static/xlsl/';
            $filePath = $filePrefix . $filename;
            $fullPath = root_path() . 'public/' . $filePrefix;
            if (file_exists($fullPath . $filename)) {
                return $filePath;
            }
            if (!file_exists($fullPath)) {
                mkdir($fullPath, 0755);
            }
            $writer->save($fullPath . $filename);
            /* 释放内存 */
            $spreadsheet->disconnectWorksheets();
            unset($objSpreadsheet);

            return $this->success(['file_path' => $filePath, 'domain' => $this->request->domain()]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage() . $exception->getLine());
        }
    }
}